# Copyright (c) 2025, EAM Team and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document


class QRCodeMaintenanceRequest(Document):
    def autoname(self):
        """自动生成报修单号"""
        from frappe.utils import now_datetime
        now = now_datetime()
        year = now.year
        
        # 获取当年的序号
        count = frappe.db.count("QR Code Maintenance Request", 
                               filters={"creation": [">=", f"{year}-01-01"]}) + 1
        
        self.request_id = f"QR-{year}-{count:05d}"
        self.name = self.request_id

    def validate(self):
        """验证数据"""
        if not self.report_time:
            self.report_time = frappe.utils.now()
        
        if not self.reporter:
            self.reporter = frappe.session.user

    def on_submit(self):
        """提交报修申请"""
        self.status = "待分配"
        self.notify_supervisor()
        self.create_equipment_history()

    def assign_technician(self, technician, supervisor):
        """主管分配维修员"""
        self.assigned_technician = technician
        self.assigned_supervisor = supervisor
        self.assignment_time = frappe.utils.now()
        self.status = "已分配"
        self.save()
        self.notify_technician()

    def accept_work_order(self, technician=None):
        """维修员接单"""
        # 如果没有指定维修员且允许自主接单
        if not self.assigned_technician and self.can_self_assign:
            if not technician:
                technician = frappe.session.user
            self.assigned_technician = technician
            self.accepted_by = technician
            self.status = "已接单"
        else:
            # 只有指派的维修员才能接单
            if frappe.session.user != self.assigned_technician:
                frappe.throw("只有指派的维修员才能接单")
            self.accepted_by = self.assigned_technician
            self.status = "已接单"
        
        self.accepted_time = frappe.utils.now()
        self.save()
        
        # 更新设备状态
        equipment = frappe.get_doc("Equipment", self.equipment)
        equipment.status = "维修中"
        equipment.save()

    def complete_work_order(self, work_summary, spare_parts_used=None):
        """完成维修工单"""
        self.completion_time = frappe.utils.now()
        self.status = "已完成"
        self.work_summary = work_summary
        
        # 恢复设备状态
        equipment = frappe.get_doc("Equipment", self.equipment)
        equipment.status = "使用中"
        equipment.last_maintenance_date = self.completion_time
        equipment.save()
        
        self.save()
        self.create_equipment_history()

    def notify_supervisor(self):
        """通知主管"""
        # 发送实时通知
        frappe.publish_realtime(
            event="new_maintenance_request",
            message={
                "request_id": self.request_id,
                "equipment": self.equipment,
                "urgency_level": self.urgency_level,
                "fault_type": self.fault_type
            },
            user="Maintenance Supervisor"
        )

    def notify_technician(self):
        """通知维修员"""
        if self.assigned_technician:
            frappe.publish_realtime(
                event="maintenance_assignment",
                message={
                    "request_id": self.request_id,
                    "equipment": self.equipment,
                    "urgency_level": self.urgency_level
                },
                user=self.assigned_technician
            )

    def create_equipment_history(self):
        """创建设备履历记录"""
        try:
            if self.status == "待分配":
                record_type = "故障报修"
                description = f"设备故障报修：{self.fault_description}"
            elif self.status == "已完成":
                record_type = "故障维修"
                description = f"故障维修完成：{self.work_summary}"
            else:
                return
                
            history = frappe.get_doc({
                "doctype": "Equipment History",
                "equipment": self.equipment,
                "record_type": record_type,
                "description": description,
                "operator": self.reporter if self.status == "待分配" else self.accepted_by,
                "related_document_type": "QR Code Maintenance Request",
                "related_document": self.name,
                "record_date": frappe.utils.now()
            })
            history.insert()
        except Exception as e:
            frappe.log_error(f"创建设备履历失败: {str(e)}", "QR Code Maintenance Request History")